package com.commons.tools.utils;

import cn.hutool.core.date.*;
import cn.hutool.core.io.*;

import lombok.extern.slf4j.*;
import org.springframework.stereotype.*;

import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.nio.charset.*;
import java.util.*;

/**
 * @author
 * @Description 文件处理工具类
 * @date 2023/7/26
 */
@Slf4j
@Component
public class FileLoadUtil {

    /**
     * 文件类型
     */
    public static final String fileType = "csv,docx,doc";

    /**
     * 文件大小
     */
    public static final Long fileSize = 50L;

    /**
     * 文件存储
     */
    public static final String fileDir = "/upload";


    private static final String MSIE = "MSIE";
    private static final String FIREFOX = "Firefox";
    private static final String CHROME = "Chrome";

    public static final Long FILE_UNIT = 1048576L; // 1MB

    public static final String NO_EXIST_FILE = "文件不存在";


    private FileLoadUtil() {
    }

    /**
     * 获取上传路径
     *
     * @return
     */
    public static String getUploadPath() {
        StringBuilder sb = new StringBuilder();
        String separator = File.separator;
        sb.append(fileDir)
                .append(DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN))
                .append(separator);
        File outFile = FileUtil.newFile(sb.toString());
        if (!outFile.exists()) {
            boolean b = outFile.mkdirs();
            if (b) {
                log.info("文件夹创建成功:{}", outFile.getPath());
            }
        }
        return sb.toString();
    }

    /**
     * 获取上传路径
     *
     * @return
     */
    public static String getDownPath() {
        StringBuilder sb = new StringBuilder();
        String separator = File.separator;
        sb.append(fileDir)
                .append(separator);
        return sb.toString();
    }

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param response 输出流
     * @return
     */
    public static void writeBytes(String filePath, HttpServletResponse response) throws Exception {
        //文件对象
        File file = FileUtil.newFile(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在");
        }
        //文件流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("文件下载失败");
        }
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        //文件名称
        String filename = fileName;
        if (agent.contains(MSIE)) {
            // IE浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            filename = filename.replace("+", " ");
        } else if (agent.contains(FIREFOX)) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
        } else if (agent.contains(CHROME)) {
            // google浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
        }
        return filename;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) {
        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(realFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(realFileName);
        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }
}
